using System.IO;
using System.Data;
using YiSha.Enum.OrganizationManage;
using YiSha.Enum;
using YiSha.Service.SystemManage;

namespace YiSha.Service.OrganizationManage;

public class UserService : RepositoryFactory
{
    #region 获取数据
    public async Task<List<UserEntity>> GetList(UserListParam param)
    {
        var expression = ListFilter(param);
        var list = await this.BaseRepository().FindList(expression);
        return list.ToList();
    }

    public async Task<List<UserEntity>> GetPageList(UserListParam param, Pagination pagination)
    {
        var expression = ListFilter(param);
        var list = await this.BaseRepository().FindList(expression, pagination);
        return list.ToList();
    }

    public async Task<UserEntity> GetEntity(long id)
    {
        return await this.BaseRepository().FindEntity<UserEntity>(id);
    }

    public async Task<UserEntity> GetEntity(string userName)
    {
        return await this.BaseRepository().FindEntity<UserEntity>(p => p.UserName == userName);
    }

    public async Task<UserEntity> CheckLogin(string userName)
    {
        var expression = LinqExtensions.True<UserEntity>();
        expression = expression.And(t => t.UserName == userName);
        expression = expression.Or(t => t.Mobile == userName);
        expression = expression.Or(t => t.Email == userName);
        return await this.BaseRepository().FindEntity(expression);
    }

    public bool ExistUserName(UserEntity entity)
    {
        var expression = LinqExtensions.True<UserEntity>();
        expression = expression.And(t => t.BaseIsDelete == 0);
        if (entity.Id.IsNullOrZero())
        {
            expression = expression.And(t => t.UserName == entity.UserName);
        }
        else
        {
            expression = expression.And(t => t.UserName == entity.UserName && t.Id != entity.Id);
        }
        return this.BaseRepository().IQueryable(expression).Count() > 0 ? true : false;
    }
    #endregion

    #region 提交数据
    public async Task UpdateUser(UserEntity entity)
    {
        await this.BaseRepository().Update(entity);
    }

    public async Task SaveForm(UserEntity entity)
    {
        var db = await this.BaseRepository().BeginTrans();
        try
        {
            if (entity.Id.IsNullOrZero())
            {
                await entity.Create();
                await db.Insert(entity);
            }
            else
            {
                await db.Delete<UserBelongEntity>(t => t.UserId == entity.Id);

                // 密码不进行更新，有单独的方法更新密码
                entity.Password = null;
                await entity.Modify();
                await db.Update(entity);
            }
            // 职位
            if (!string.IsNullOrEmpty(entity.PositionIds))
            {
                foreach (long positionId in TextHelper.SplitToArray<long>(entity.PositionIds, ','))
                {
                    UserBelongEntity positionBelongEntity = new UserBelongEntity();
                    positionBelongEntity.UserId = entity.Id;
                    positionBelongEntity.BelongId = positionId;
                    positionBelongEntity.BelongType = UserBelongTypeEnum.Position.ParseToInt();
                    await positionBelongEntity.Create();
                    await db.Insert(positionBelongEntity);
                }
            }
            // 角色
            if (!string.IsNullOrEmpty(entity.RoleIds))
            {
                foreach (long roleId in TextHelper.SplitToArray<long>(entity.RoleIds, ','))
                {
                    UserBelongEntity departmentBelongEntity = new UserBelongEntity();
                    departmentBelongEntity.UserId = entity.Id;
                    departmentBelongEntity.BelongId = roleId;
                    departmentBelongEntity.BelongType = UserBelongTypeEnum.Role.ParseToInt();
                    await departmentBelongEntity.Create();
                    await db.Insert(departmentBelongEntity);
                }
            }
            await db.CommitTrans();
        }
        catch
        {
            await db.RollbackTrans();
            throw;
        }
    }

    public async Task DeleteForm(string ids)
    {
        var db = await this.BaseRepository().BeginTrans();
        try
        {
            long[] idArr = TextHelper.SplitToArray<long>(ids, ',');
            await db.Delete<UserEntity>(idArr);
            await db.Delete<UserBelongEntity>(t => idArr.Contains(t.UserId.Value));
            await db.CommitTrans();
        }
        catch
        {
            await db.RollbackTrans();
            throw;
        }
    }

    public async Task ResetPassword(UserEntity entity)
    {
        await entity.Modify();
        await this.BaseRepository().Update(entity);
    }

    public async Task ChangeUser(UserEntity entity)
    {
        await entity.Modify();
        await this.BaseRepository().Update(entity);
    }
    #endregion

    #region 私有方法
    private Expression<Func<UserEntity, bool>> ListFilter(UserListParam param)
    {
        //新增/编辑部门时param为null，此时初始化默认实例以防异常
        if (null == param)
        {
            param = new UserListParam();
        }

        //下面LinqExtensions.GetExpressionItems获取Expression时排除这些非表字段属性
        var userIds = param.UserIds;
        param.UserIds = null;
        var startTime = param.StartTime;
        param.StartTime = null;
        var endTime = param.EndTime;
        param.EndTime = null;
        var childrenDepartmentIdList = param.ChildrenDepartmentIdList;
        param.ChildrenDepartmentIdList = null;

        //var expression = LinqExtensions.True<UserEntity>();

        if (param.UserStatus == -1)
        {
            param.UserStatus = null;
        }

        //****根据查询字段自动过滤条件****
        var expression = LinqExtensions.GetExpressionItems<UserEntity, UserListParam>(param);

        //if (!string.IsNullOrEmpty(param.UserName))
        //{
        //    expression = expression.And(t => t.UserName.Contains(param.UserName));
        //}


        if (userIds?.Length>0)
        {
            long[] userIdList = userIds;// TextHelper.SplitToArray<long>(userIds, ',');
            expression = expression.And(t => userIdList.Contains(t.Id.Value));
        }

        //if (!string.IsNullOrEmpty(param.Mobile))
        //{
        //    expression = expression.And(t => t.Mobile.Contains(param.Mobile));
        //}
        //if (param.UserStatus > -1)
        //{
        //    expression = expression.And(t => t.UserStatus == param.UserStatus);
        //}

        if (!string.IsNullOrEmpty(startTime.ParseToString()))
        {
            expression = expression.And(t => t.BaseModifyTime >= startTime);
        }
        if (!string.IsNullOrEmpty(endTime.ParseToString()))
        {
            endTime = endTime.Value.Date.Add(new TimeSpan(23, 59, 59));
            expression = expression.And(t => t.BaseModifyTime <= endTime);
        }
        if (childrenDepartmentIdList != null && childrenDepartmentIdList.Count > 0)
        {
            expression = expression.And(t => childrenDepartmentIdList.Contains(t.DepartmentId.Value));
        }

        return expression;
    }
    #endregion
}